package com.blue.http.filter;

import com.blue.http.message.HttpRequest;
import com.blue.http.message.HttpResponse;
import com.blue.http.util.HttpException;
import io.prometheus.client.Summary;

/**
 * @author zhengjin
 * @since 1.0 2018年12月30日
 */
public class PrometheusFilter implements Filter
{
	private ThreadLocal<Long> startLocal;
	private Summary summary;

	public PrometheusFilter()
	{
		startLocal = new ThreadLocal<>();
		summary = Summary.build("summary_http_request", "Http Request Latency Summary")
				.labelNames("path", "method", "code")
				.register();
	}

	@Override
	public boolean preHandle(HttpRequest request, HttpResponse response) throws HttpException
	{
		startLocal.set(System.currentTimeMillis());
		return true;
	}

	@Override
	public void afterHandle(HttpRequest request, HttpResponse response, Exception e)
	{
		long start = startLocal.get();
		startLocal.remove();
		long used = System.currentTimeMillis() - start;
		summary.labels(request.getUrl(), request.getHttpMethod().name(), String.valueOf(response.getCode()))
				.observe(used / 1000.0d);
	}
}
